﻿using System;
using Microsoft.EntityFrameworkCore;

namespace FlashPay.DAO.Impl.Order
{
    using FlashPay.DAO.Order;
    using FlashPay.DAO.Shared;
    using FlashPay.EF;
    using FlashPay.EF.Models;
    using FlashPay.Entity;
    using FlashPay.Entity.Parameter;
    using FlashPay.Entity.Response.Order;
    using FlashPay.Util;
    using System.Collections.Generic;
    using System.Linq;
    using System.Linq.Expressions;

    /// <summary>
    /// 訂單詳情DAO
    /// </summary>

    public class OrderRecordDetailDaoImpl : BaseDAO, OrderRecordDetailDao
    {
        #region 注入
        /// <summary>
        /// EF上下文
        /// </summary>
        private FlashPayContext _context { set; get; }

        /// <summary>
        /// 注入
        /// </summary>
        /// <param name="context"></param>
        public OrderRecordDetailDaoImpl(FlashPayContext context)
        {
            _context = (FlashPayContext)context;
        }

        public void Dispose()
        {
            if (_context != null)
            {
                _context.Dispose();
            }
        }
        #endregion



        /// <summary>
        /// 根据编号获取订单明细
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>SysRole</returns>
        public OrderRecordDetailResponse Get(int detailId)
        {
            var q = from ord in _context.OrderRecordDetail
                    join
                    or in _context.OrderRecord on ord.OrderNo equals or.OrderNo
                    join
                    bc in _context.BankInfo on ord.BankCode equals bc.BankCode
                    where 
                    ord.DetailId == detailId
                    select new {
                        //cm.CardCommissionerUid,
                        ord.DetailId,
                        ord.OrderNo,
                        ord.BankCode,
                        ord.OrderQuantity,
                        ord.UnitPrice,
                        ord.ActualQuantity,
                        ord.ActualUnitPrice,
                        ord.Remark,
                        ord.CreateUid,
                        ord.CreateDate,

                        or.DepositUid,
                        or.ReceiptUid,
                        or.PayUid,

                        OrderCreateUid = or.CreateUid,

                        bc.BankName
                    };

            var model = q.FirstOrDefault();

            return new OrderRecordDetailResponse()
            {
                //CardCommissionerUid = model.CardCommissionerUid,

                DetailID = model.DetailId,
                OrderNo = model.OrderNo.ToString(),
                BankCode = model.BankCode,
                OrderQuantity = model.OrderQuantity,
                UnitPrice = model.UnitPrice.ToString("#0.00"),
                ActualQuantity = model.ActualQuantity,
                ActualUnitPrice = model.ActualUnitPrice.ToString("#0.00"),
                Remark = model.Remark,
                CreateUID = model.CreateUid,
                CreateDate = model.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),

                BankName = model.BankName,

                DepositUid = model.DepositUid,
                ReceiptUid = model.ReceiptUid,
                PayUid = model.PayUid,

                OrderCreateUID = model.OrderCreateUid
            };
        }

        /// <summary>
        /// 根据编号获取系统订单
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>SysRole</returns>
        public OrderRecordDetail GetOrderRecordDetail(long DetailId)
        {
            return _context.OrderRecordDetail.Where(x => x.DetailId == DetailId).FirstOrDefault();
        }

        /// <summary>
        /// 根据编号获取系统订单
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>SysRole</returns>
        public OrderRecord GetOrderRecord(long orderNo)
        {
            return _context.OrderRecord.Where(x => x.OrderNo == orderNo).FirstOrDefault();
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="userInfo">新增对象</param>
        /// <returns></returns>
        public JResult<OrderRecordDetail> Add(OrderRecordDetail model)
        {
            var result = new JResult<OrderRecordDetail>()
            {
                Success = false
            };

            try
            {
                _context.OrderRecordDetail.Add(model);
                _context.SaveChanges();

                result.Success = true;
                result.Data = model;
            }
            catch (Exception ex)
            {
                result.ErrorMessage = ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="model"></param>
        public bool Update(OrderRecordDetail model)
        {
            bool result = false;

            var orderRecordDetail = _context.OrderRecordDetail.Find(model.DetailId);
            if (orderRecordDetail != null)
            {
                orderRecordDetail.BankCode = model.BankCode;
                orderRecordDetail.OrderQuantity = model.OrderQuantity;
                orderRecordDetail.UnitPrice = model.UnitPrice;
                orderRecordDetail.ActualQuantity = model.ActualQuantity;
                orderRecordDetail.ActualUnitPrice = model.ActualUnitPrice;
                orderRecordDetail.Remark = model.Remark;

                _context.Entry<OrderRecordDetail>(orderRecordDetail);
                _context.SaveChanges();
                result = true;
            }

            return result;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="detailId">系统编号</param>
        /// <returns></returns>
        public bool DeleteByDetailId(int detailId)
        {

            //实例化一个UserInfo对象，并指定Id的值
            var orderRecordDetail = _context.OrderRecordDetail.Where(x => x.DetailId == detailId).FirstOrDefault();
            //将UserInfo附加到上下文对象中，并获得EF容器的管理对象
            var result = _context.Entry<OrderRecordDetail>(orderRecordDetail);
            //设置该对象的状态为删除
            result.State = EntityState.Deleted;
            //保存修改
            _context.SaveChanges();

            return true;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>PagedList<Permission></returns>
        public PagedList<OrderRecordDetailResponse> GetPager(OrderRecordDetailQuery query)
        {

            var q = from ord in _context.OrderRecordDetail
                    join
                    or in _context.OrderRecord on ord.OrderNo equals or.OrderNo
                    join
                    bc in _context.BankInfo on ord.BankCode equals bc.BankCode
                    where ord.OrderNo == query.OrderNo
                    orderby ord.CreateDate descending
                    select new
                    {
                        //cm.CardCommissionerUid,
                        ord.DetailId,
                        ord.OrderNo,
                        ord.BankCode,
                        ord.OrderQuantity,
                        ord.UnitPrice,
                        ord.ActualQuantity,
                        ord.ActualUnitPrice,
                        ord.Remark,
                        ord.CreateUid,
                        ord.CreateDate,

                        or.DepositUid,
                        or.ReceiptUid,
                        or.PayUid,

                        OrderCreateUid = or.CreateUid,

                        bc.BankName
                    };

            var list = q.Skip((query.CurrentPageIndex.Value - 1) * query.PageSize.Value).Take(query.PageSize.Value).ToList();

            var orderRecordDetailResponses = new List<OrderRecordDetailResponse>();

            list.ForEach(item => {
                orderRecordDetailResponses.Add(new OrderRecordDetailResponse() {
                    //CardCommissionerUid = item.CardCommissionerUid,
                    DetailID = item.DetailId,
                    OrderNo = item.OrderNo.ToString(),
                    BankCode = item.BankCode,
                    OrderQuantity = item.OrderQuantity,
                    UnitPrice = item.UnitPrice.ToString("#0.00"),
                    ActualQuantity = item.ActualQuantity,
                    ActualUnitPrice = item.ActualUnitPrice.ToString("#0.00"),
                    Remark = item.Remark,
                    CreateUID = item.CreateUid,
                    CreateDate = item.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),

                    BankName = item.BankName,

                    DepositUid = item.DepositUid,
                    ReceiptUid = item.ReceiptUid,
                    PayUid = item.PayUid,
                    
                    OrderCreateUID = item.OrderCreateUid
                });
            });

            return new PagedList<OrderRecordDetailResponse>()
            {
                TotalCount = q.Count(),
                TData = orderRecordDetailResponses,
                Success = true,
            };
        }

        /// <summary>
        /// 订单明细查找
        /// </summary>
        /// <param name="query">参数</param>
        public List<OrderRecordDetail> GetList(OrderRecordDetailQuery query)
        {
            //多条件查询
            var where = PredicateBuilder.True<OrderRecordDetail>();

            if (query.NoEqualDetailId.HasValue)
            {
                where = where.And(c => c.DetailId != query.NoEqualDetailId.Value);
            }
            //订单编号
            if (query.OrderNo>0)
            {
                where = where.And(c => c.OrderNo == query.OrderNo);
            }
            //银行编码
            if (!string.IsNullOrEmpty(query.BankCode))
            {
                where = where.And(c => c.BankCode == query.BankCode);
            }

            var list = _context.OrderRecordDetail.Where(where.Compile()).ToList();

            return list;
        }

        #region 老代码
        /// <summary>
        /// 訂單詳情新增
        /// </summary>
        public void Add(BaseModel<String> result, OrderRecordDetail model)
        {
            /* 呼叫資料庫 */
            _context.OrderRecordDetail.Add(model);
            _context.SaveChanges();

            /* 結果複製 */
            result.Success = true;
        }

        /// <summary>
        /// 訂單詳情修改
        /// </summary>
        public void EditUseDetailId(BaseModel<String> result, OrderRecordDetail model)
        {
            /* 確認資料存在 */
            Int32 detailId = model.DetailId;
            IQueryable<OrderRecordDetail> _result = _context.OrderRecordDetail.Where(x => x.DetailId == detailId);
            if (_result.Count() != 1)
                return;

            /* 轉換Model */
            OrderRecordDetail orderRecordDetail = _result.First();
            orderRecordDetail.BankCode = model.BankCode;
            orderRecordDetail.OrderQuantity = model.OrderQuantity;
            orderRecordDetail.UnitPrice = model.UnitPrice;
            orderRecordDetail.ActualQuantity = model.ActualQuantity;
            orderRecordDetail.ActualUnitPrice = model.ActualUnitPrice;
            orderRecordDetail.Remark = model.Remark;

            /* 呼叫資料庫 */
            _context.SaveChanges();

            /* 結果複製 */
            result.Success = true;
        }

        /// <summary>
        /// 訂單詳情刪除
        /// </summary>
        public void DeleteUseDetailId(BaseModel<String> result, OrderRecordDetail model)
        {
            /* 確認資料存在 */
            Int32 detailId = model.DetailId;
            IQueryable<OrderRecordDetail> _result = _context.OrderRecordDetail.Where(x => x.DetailId == detailId);
            if (_result.Count() != 1)
                return;

            /* 呼叫資料庫 */
            _context.OrderRecordDetail.Remove(_result.First());
            _context.SaveChanges();

            /* 結果複製 */
            result.Success = true;
        }

        /// <summary>
        /// 訂單詳情列表
        /// </summary>
        public void Get(BaseModel<List<OrderRecordDetail>> result, OrderRecordDetail model)
        {
            /* 呼叫資料庫 */
            IQueryable<OrderRecordDetail> _result = _context.OrderRecordDetail.Where(
                orderRecordDetail => 
                    (model.DetailId < 1 || orderRecordDetail.DetailId == model.DetailId) &&
                    (model.OrderNo < 1 || orderRecordDetail.OrderNo == model.OrderNo)
            );

            List<OrderRecordDetail> list = Split(_result.OrderByDescending(orderRecordDetail => orderRecordDetail.OrderNo), result.PageIndex, result.PageSize);

            /* 結果複製 */
            result.Success = true;
            result.TotalCount = _result.Count();
            result.Result = list;
        }
        #endregion


    }
}
